//
//  HomeViewController.swift
//  CJPWB
//
//  Created by 陈锦彭 on 16/3/12.
//  Copyright © 2016年 chenjinpeng. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh
class HomeViewController: BaseViewController {
  // MARK: - 属性
    lazy var titleBtn : TitleBtn = TitleBtn()
    lazy var popoverAnimationor : PopoverAnimationor = PopoverAnimationor()
    ///视图模型数据
    lazy var statusViewModelArray  = [StatusViewModel]()
    lazy var cellHeightCache : [String : CGFloat] = [String : CGFloat]()//缓存cell的高度
    ///刷新提示的label
    lazy var tipLabel : UILabel = UILabel()
    override func viewDidLoad() {
        super.viewDidLoad()
        if !isLogin {
            ///加载旋转背景动画
            visitorView.roationViewToRoation()
            return
        }
        
        //设置导航条的内容
        setupNavigationItem()
        
        //设置下拉和上拉刷新
        setupRefresh()
        
        //自动计算cell的高度
//        tableView.estimatedRowHeight = 200
//        tableView.rowHeight = UITableViewAutomaticDimension
    }
    
    
}

// MARK: - UI的基本设置
extension HomeViewController {
    //设置导航条的内容
    private func setupNavigationItem() {
       //左边的UIBarButtonItem
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: "leftBarButtonItemDidClick")
        //右边的UIBarButtonItem
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "rightBarButtonItemDidClick")
        
        //中间标题按钮的设置
        titleBtn.setTitle("独钓寒江雪", forState: .Normal)
        
        titleBtn.addTarget(self, action: "titleViewDidClick:", forControlEvents: .TouchUpInside)
        navigationItem.titleView = titleBtn
        
    }
    
    //设置下拉刷新
    private func setupRefresh() {
         //1.创建headerView
        let headerView = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewData")
        headerView.setTitle("下拉进入刷新", forState: .Idle)
        headerView.setTitle("正在刷新...", forState: .Refreshing)
        headerView.setTitle("松手进入刷新", forState: .Pulling)
        tableView.mj_header = headerView
        
        // 2.进入刷新状态
        tableView.mj_header.beginRefreshing()
        
        //3.添加提示的label
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        
        tipLabel.frame = CGRect(x: 0, y: 14, width: screenW, height: 30)
        tipLabel.text = "刷新了条微博"
        tipLabel.backgroundColor = UIColor.orangeColor()
        tipLabel.textAlignment = .Center
        tipLabel.hidden = true
        tipLabel.textColor = UIColor(white: 1.0, alpha: 1.0)
        
    }
    
    
    

    
}

// MARK: - UIBarButtonItem 的点击事件处理
extension HomeViewController {
    ///左边的UIBarButtonItem
    @objc private func leftBarButtonItemDidClick() {
    print("leftBarButtonItemDidClick")
    }
    
    ///右边的UIBarButtonItem
    @objc private func rightBarButtonItemDidClick() {
        print("rightBarButtonItemDidClick")
    }
    
    ///中间标题的点击事件
    @objc private func titleViewDidClick(titleBtn : UIButton) {
        
        //转场动画的设置
        let popoverVC = PopoverViewController()
        //设置弹出的模式为自定义,这样子不会隐藏后面的视图
        popoverVC.modalPresentationStyle = .Custom
        //设置转场动画代理
        popoverAnimationor.presentedFrame = CGRect(x: 120, y: 60, width: 180, height: 250)
        popoverAnimationor.animateCallBack = {[weak self](isPresent : Bool) -> () in
            //按钮的选中判断
            self?.titleBtn.selected = isPresent
        }
        popoverVC.transitioningDelegate = popoverAnimationor
        
        presentViewController(popoverVC, animated: true, completion: nil)
       
        
    }

}

// MARK: - 数据源方法
extension HomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusViewModelArray.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let stastatusViewModel = statusViewModelArray[indexPath.row]
        //1.创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier("homeCell") as! HomeTableViewCell
        //2.给cell设置数据
        cell.statusViewModel = stastatusViewModel
        if indexPath.row == statusViewModelArray.count - 1 {
          loadMoreData()
        }
        //3.返回cell
        return cell
    }
    
    //计算cell的高度
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let statusViewModel = statusViewModelArray[indexPath.row]
        //key
        let key = statusViewModel.status!.id
        //从缓存里取出cell的高度
         var cellHeight = cellHeightCache["\(key)"]
          if cellHeight != nil {
          return cellHeight!
        }
        //1.创建cell
        let cell = tableView.dequeueReusableCellWithIdentifier("homeCell") as! HomeTableViewCell
        //2.给cell设置数据
          cellHeight = cell.cellHeight(statusViewModel)
        
        //把cell的高度存进缓存中
        cellHeightCache["\(key)"] = cellHeight
        return cellHeight!
    }

}


// MARK: - 加载数据
extension HomeViewController {
    ///加载最新数据
   @objc private func loadNewData() {
     loadStatus(true)
        
    }
    
    ///加载更多数据
    @objc private func loadMoreData() {
    loadStatus(false)
    }
    
    ///加载数据
    private func loadStatus(isNew : Bool) {
        var since_id = 0
        var max_id = 0
        if isNew {
         since_id = statusViewModelArray.first?.status?.id ?? 0
        }else {
         max_id = statusViewModelArray.last?.status?.id ?? 0
          max_id = max_id == 0 ? 0 : max_id - 1
        }
        HttpRequestTool.shareInstance.loadStatuses(since_id, max_id: max_id) { (isSuccess, error) -> () in
            //1.加载失败
            if error != nil {
                self.tableView.mj_header.endRefreshing()
                print(error)
                return
            }
            
            guard let resultArray = isSuccess else {
                self.tableView.mj_header.endRefreshing()
                return
            }
            var modelArray = [StatusViewModel]()
            for dict in resultArray {
                //2.数据转模型
                let status = Status(dict: dict)
                let statusViewModel = StatusViewModel(status: status)
                modelArray.append(statusViewModel)
                
            }
            
            //判断上拉还是下拉来确定是新数据还是旧数据
            if isNew {
            self.statusViewModelArray = modelArray + self.statusViewModelArray
            }else {
            self.statusViewModelArray += modelArray
            }
            
            //3.缓存图片
            self.imageCache(modelArray.count)
            
        }

    }
    
    //缓存图片
    private func imageCache(count : Int) {
        //1.创建下载组
        let group = dispatch_group_create()
        for statusViewModel in statusViewModelArray{
            for url in statusViewModel.pictureUrls{
                //2.将任务加紧下载组中
                dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in

                //3.将任务宠组中移除
                dispatch_group_leave(group)
            })
        }
           
    }
        //4.下载完毕刷新表格
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            //4.刷新表格
            self.tableView.reloadData()
            //结束刷新
            self.tableView.mj_header.endRefreshing()
            //给tipLabel添加动画
           self.showTipLabelAnimate(count)
        })
  }
    
    ///给tipLabel添加动画
    private func showTipLabelAnimate(count : Int) {
        //设置tipLabel的内容
        tipLabel.hidden = false
        tipLabel.text = count == 0 ? "没有新微博" : "刷新了\(count)条微博"
        
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
            }, completion: { (_) -> Void in
                UIView.animateWithDuration(0.25, delay: 2, options: [], animations: { () -> Void in
                    
                    self.tipLabel.frame.origin.y = 14
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
        })
    }
    
    
}


